﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using QD.Config;
using System.Text.RegularExpressions;

namespace QD.UrlRewriter
{
    public class RewriteUrlModule : IHttpModule
    {

        private readonly static object lockObject = new object();
        private readonly static ConfigInfo config = Configs.Instance().GetConfig();



        public void Init(HttpApplication context)
        {
            context.BeginRequest += new EventHandler(context_BeginRequest);
        }

        void context_BeginRequest(object sender, EventArgs e)
        {
            try
            {
                HttpContext context = ((HttpApplication)sender).Context;
                string requestPath = context.Request.Path.ToString().ToLower();
               
                if (requestPath == "/index" + config.UrlExt || requestPath == "/")
                {
                    context.RewritePath("/index.aspx");
                    return;
                }


                lock (lockObject)
                {
                    string sendToUrl = null;
                    foreach (mRewriteUrl u in RewriteConfig.Instance().GetRewriteUrls().Urls)
                    {
                        if (Regex.IsMatch(requestPath, u.Lookfor, RegexOptions.IgnoreCase))
                        {
                            sendToUrl = Regex.Replace(requestPath, u.Lookfor, u.Sendto, RegexOptions.Compiled | RegexOptions.IgnoreCase);
                            break;
                        }
                    }
                    if (!string.IsNullOrEmpty(sendToUrl))
                    {
                        this.RewriteUrl(context, "/" + sendToUrl);
                        return;
                    }

                    return;
                }

            }
            catch (Exception ex)
            {

            }
        }

        private void RewriteUrl(HttpContext context, string sendToUrl)
        {
            if (context.Request.QueryString.Count > 0)
            {
                if (sendToUrl.IndexOf('?') != -1)
                {
                    sendToUrl = sendToUrl + "&" + context.Request.QueryString.ToString();
                }
                else
                {
                    sendToUrl = sendToUrl + "?" + context.Request.QueryString.ToString();
                }
            }
            string queryString = string.Empty;
            string requestPagge = sendToUrl;
            if (sendToUrl.IndexOf('?') > 0)
            {
                requestPagge = sendToUrl.Substring(0, sendToUrl.IndexOf('?'));
                queryString = sendToUrl.Substring(sendToUrl.IndexOf('?') + 1);
            }
            context.RewritePath(requestPagge, string.Empty, queryString);
        }

        public void Dispose()
        {
            return;
        }


    }

}
